﻿// Sheego.Service.X400
// Copyright(C) 2015 Schwab Versand GmbH
//
// This source file is subject to the Microsoft Public License(Ms-PL).
// http://www.opensource.org/licenses/ms-pl.html
// All other rights reserved.
using Sheego.Service.X400.Job.Shared;
using Sheego.Service.X400.Job.Shared.BO;
using Sheego.Service.X400.Job.Shared.Processor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sheego.Service.X400.Job.Impl.Processor
{
    class ArchiveMessageProcessor : IX400MessageProcessor
    {
        private string Directory = null;
        private IFileManager FileManager;
        public ArchiveMessageProcessor(IFileManager fileManager)
        {
            FileManager = fileManager;
        }
        #region IX400MessageProcessor Members

        public void Process(IX400Message Message)
        {
            if (FileManager == null)
                throw new ArgumentNullException("FileManager");

            if (Message == null)
                throw new ArgumentNullException("Message");


            var FileNamePrefix = Directory + @"\" + FileManager.CreateUniquePattern(DateTime.Now);
            int cnt = 0;
            //TODO WriteHeader
            StringBuilder header = new StringBuilder();


            header.AppendFormat("P2Originator   : {0}\r\n", Message.P2Originator);
            header.AppendFormat("P7Originator   : {0}\r\n", Message.P7Originator);
            header.AppendFormat("Subject        : {0}\r\n", Message.Subject);
            header.AppendFormat("SubmissionTime : {0}\r\n", Message.SubmissionTime);
            header.AppendFormat("CreationTime   : {0}\r\n", Message.CreationTime);


            foreach (var MsgPart in Message.MessageParts)
            {
                //Write MessagePart
                FileManager.WriteFile(FileNamePrefix+"_Part"+(cnt)+".bin", MsgPart.Content);
                header.AppendFormat("MessagePart{0}-ContentType   : {1}\r\n", cnt, MsgPart.ContentType);
                header.AppendFormat("MessagePart{0}-ContentLength : {1}\r\n", cnt, MsgPart.ContentLength);
                cnt++;
            }

            FileManager.WriteTextFile(FileNamePrefix + "_Head.txt", header.ToString());

        }

        public void Config(string Key, string Value)
        {
            if (string.IsNullOrWhiteSpace(Key))
                throw new ArgumentNullException("Key");
            if (string.IsNullOrWhiteSpace(Value))
                throw new ArgumentNullException("Value");

            //Directory
            if (Key.Equals("Directory"))
            {
                Directory = Value;
                return;
            }

            throw new KeyNotFoundException(Key);
        }

        #endregion
    }
}
